package com.open.pingban.fragment;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.open.pingban.MainActivity;
import com.open.pingban.R;
import com.open.pingban.mode.CameraData;
import com.open.pingban.mode.CameraInfo;
import com.open.pingban.mode.GpsDataInfo;
import com.open.pingban.presenter.IMonitoringContract;
import com.open.pingban.utils.Constant;
import com.open.pingban.utils.OPENLOG;
import com.open.pingban.view.FlipShareView;
import com.open.pingban.view.KuMeiPlayer;
import com.open.pingban.view.ShareItem;

import org.video.stream.CoreLib;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
//import io.vov.vitamio.MediaPlayer;
//import io.vov.vitamio.widget.VideoView;

/**
 * 实时监控界面.
 */
public class RealTimeMonitoringFragment extends BaseView implements IMonitoringContract.View {

    private static final String WEB_VIEW_URL = "http://f117cdh.gnway.cc/planevod/google/google_js/api.html";
    private static final String GPS_URL = "ws://f117cdh.gnway.cc:81/gps";
    private static final int MENU_SELECT_TEXT_COLOR = Color.WHITE;
    private static final int MENU_SELECT_BG_COLOR = 0xff57708A;

    @InjectView(R.id.switch_btn)
    View switchBtn;
    @InjectView(R.id.switch_tv)
    TextView switchTv;
    @InjectView(R.id.gps_state_tv)
    TextView gpsStateTv;
    @InjectView(R.id.speed_tv)
    TextView speedTv;
    @InjectView(R.id.location_tv)
    TextView locationTv;

    private final WebSocketConnection mConnection = new WebSocketConnection();
    @InjectView(R.id.time_tv)
    TextView timeTv;
    @InjectView(R.id.monitor_load_pb)
    ProgressBar monitorLoadPb;
    private View mRootView;
//    private VideoView mVideoView;
    private WebView mWebview;
    private int mMenuSelectIndex = -1;

    List<ShareItem> mShareItems = new ArrayList<ShareItem>();

    public RealTimeMonitoringFragment(Activity activity) {
        super(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater) {
        mRootView = inflater.inflate(R.layout.fragment_monitoring, null, false);
        ButterKnife.inject(this, mRootView);
        return mRootView;
    }

    private void initAllViews() {
        mWebview = (WebView) mRootView.findViewById(R.id.webview);
        initVideoView();
        initWebView();
    }

    private void initWebView() {
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        WebSettings settings = mWebview.getSettings();
        settings.setJavaScriptEnabled(true);
    }

    @Override
    public void updateNetWorkView() {
        mUpdateHander.sendEmptyMessageDelayed(-250, 1000);
    }

    @Override
    public void stopVideoView() {
        mKuMeiPlayer.destroy();
        isStop = true;
    }

    /**
     *  防止被重复加载，导致崩溃.
     */
    private static boolean isStop = false;

    Handler mUpdateHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                mWebview.loadUrl(WEB_VIEW_URL);
                initWebSocket(); // websocket.
                getCameraList(); /* 初始化摄像头列表 */
            } catch (Exception e) {
                OPENLOG.E("" + e.getMessage());
                e.printStackTrace();
            }
        }
    };

    KuMeiPlayer mKuMeiPlayer;

    @Override
    public void onActivityCreated() {
        OPENLOG.D("onActivityCreated==>11111");
        initAllViews();
        updateNetWorkView();
        mKuMeiPlayer = (KuMeiPlayer) mRootView.findViewById(R.id.monitoring_kumeiPlayer);
        mKuMeiPlayer.init(getActivity());
         /* 测试韩工的播放器 */
        String path = "rtmp://live.hkstv.hk.lxdns.com/live/hks";
//        path = "http://f117cdh.gnway.cc:281/zuoshang.ts";
//        mKuMeiPlayer.setVideoPath(path);
    }

    private void initVideoView() {
    }

    private void initWebSocket() {
        try {
            mConnection.connect(GPS_URL, mWebSocketHandler);
        } catch (WebSocketException e) {
            e.printStackTrace();
            OPENLOG.E("error:" + e.getMessage());
        }
    }

    /**
     * websocket handler.
     */
    WebSocketHandler mWebSocketHandler = new WebSocketHandler() {
        @Override
        public void onOpen() {
            OPENLOG.D("onOpen");
        }

        @Override
        public void onTextMessage(String payload) {
            try {
                Gson gson = new Gson();
                GpsDataInfo gpsDataInfo = gson.fromJson(payload, GpsDataInfo.class);
                Message msg = mTitleInfoHandler.obtainMessage();
                msg.obj = gpsDataInfo;
                mTitleInfoHandler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
                OPENLOG.E("error:" + e.getMessage());
            }
        }

        @Override
        public void onClose(int code, String reason) {
            OPENLOG.D("onClose code:" + code + " reason:" + reason);
        }
    };

    /**
     * gsp状态，当前速度，当前左边更新.
     */
    Handler mTitleInfoHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                GpsDataInfo gpsDataInfo = (GpsDataInfo) msg.obj;
                if (gpsDataInfo != null) {
                    if (!TextUtils.isEmpty(gpsDataInfo.getStatus())) {
                        String gpsState = gpsDataInfo.getStatus().equalsIgnoreCase("a") ? "定位" : "不定位";
                        gpsStateTv.setText("GPS状态：" + gpsState);
                    }
                    float speed = gpsDataInfo.getSpeed();
                    if (speed > 0) {
                        speedTv.setText("当前速度：" + speed + " km/h");
                    }
                    float lat = gpsDataInfo.getLat();
                    if (lat > 0) {
                        locationTv.setText("当前坐标：" + lat + "," + lat);
                    }
                    String time = gpsDataInfo.getTime();
                    if (!TextUtils.isEmpty(time)) {
                        timeTv.setText("当前时间：" + time);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @OnClick({R.id.switch_btn, R.id.switch_tv, R.id.scale_max, R.id.scale_min})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.switch_btn:
            case R.id.switch_tv:
                try {
                    FlipShareView flipShareView =
                            new FlipShareView.Builder(this.getActivity(), switchTv)
                                    .addItems(mShareItems)
                                    .setSeparateLineColor(0x30000000)
                                    .setAnimType(FlipShareView.TYPE_VERTICLE)
                                    .setItemDuration(100)
                                    .create();
                    flipShareView.setOnFlipClickListener(mOnFlipClickListener);
                } catch (Exception e) {
                    e.printStackTrace();
                    OPENLOG.E("初始化监控菜单失败... ...");
                }
                break;
            case R.id.scale_max: // 放大.
                try {
                    mConnection.sendTextMessage("zoomin:camid");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.scale_min: // 缩小
                try {
                    mConnection.sendTextMessage("zoomout:camid");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    FlipShareView.OnFlipClickListener mOnFlipClickListener = new FlipShareView.OnFlipClickListener() {
        @Override
        public void onItemClick(int position) {
            if (mShareItems.size() <= 0)
                return;
            if (mMenuSelectIndex != -1) {
                mShareItems.get(mMenuSelectIndex).bgColor = Color.WHITE;
                mShareItems.get(mMenuSelectIndex).titleColor = Color.BLACK;
            }
            mShareItems.get(position).bgColor = MENU_SELECT_BG_COLOR;
            mShareItems.get(position).titleColor = MENU_SELECT_TEXT_COLOR;
            mMenuSelectIndex = position;
            switchTv.setText("" + mShareItems.get(position).title);
            final String url = getSwitchCameraAddr();
            if (!TextUtils.isEmpty(url)) {
                Toast.makeText(getActivity(), "正在切换中 ，请等待", Toast.LENGTH_LONG).show();
                try {
//                    monitorLoadPb.setVisibility(View.VISIBLE);
                    /**
                     *  BUG: 当监控和历史同时播放的时候，跳转进入一个界面，然后返回，就崩溃了.
                     *  因为两个播放器都在加载，导致的问题.
                     */
                    ((MainActivity) getActivity()).stopAllVideoAndAudio(0);
                    mKuMeiPlayer.setVideoPath(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void dismiss() {
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mKuMeiPlayer != null) {
            mKuMeiPlayer.destroy();
            mKuMeiPlayer = null;
        }

        if (mTitleInfoHandler != null) {
            mTitleInfoHandler.removeCallbacksAndMessages(null);
        }
        closeWebSocket();
    }

    private void closeWebSocket() {
        if (mConnection.isConnected()) {
            mConnection.disconnect();
        }
    }

    /**
     * 获取所有需要切换的摄像头.
     */
    private void getCameraList() {
        OPENLOG.D(Constant.GET_CAMERA_LIST_URL);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        asyncHttpClient.get(Constant.ROOT_ADDR + Constant.GET_CAMERA_LIST_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    String data = new String(responseBody);
                    Gson gson = new Gson();
                    CameraData cameraData = gson.fromJson(data, CameraData.class);
                    if (cameraData != null) {
                        onSuccessFunction(cameraData.getData());
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onFailureFunction();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                onFailureFunction();
            }
        });
    }

    private void onSuccessFunction(final List<CameraInfo> cameraListInfos) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mShareItems.clear();
                for (CameraInfo cameraInfo : cameraListInfos) {
                    OPENLOG.D("cameraInfo:" + cameraInfo.toString());
                    if (cameraInfo.getType().equals(Constant.SWITCH_IPCAM_TYPE)) {
                        ShareItem shareItem = new ShareItem(cameraInfo.getName());
                        shareItem.id = cameraInfo.getId();
                        shareItem.videoUrl = cameraInfo.getUrl(); // 监控地址.
                        mShareItems.add(shareItem);
                    }
                }
                /* 默认切换第一个监控摄像头 */
                if (mShareItems.size() > 0 && !isStop) {
                    mOnFlipClickListener.onItemClick(0);
                }
                isStop = false;
            }
        });
    }

    private void onFailureFunction() {
        showMsg("获取摄像头数据失败");
    }

    /**
     * 获取切换视频的地址.
     */
    private String getSwitchCameraAddr() {
        String url = "";
        try {
            url = mShareItems.get(mMenuSelectIndex).videoUrl;
            Constant.VIDEO_ID = mShareItems.get(mMenuSelectIndex).id; // 用于回放搜索.
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    public static RealTimeMonitoringFragment newInstance(Activity activity) {
        RealTimeMonitoringFragment newFragment = new RealTimeMonitoringFragment(activity);
        return newFragment;
    }

}
